package com.funtonow.jqdk.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.bean.ApplyRecordBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.service.DownloadService;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.PhoneUtils;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.github.ybq.android.spinkit.SpinKitView;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;

import static com.funtonow.jqdk.base.UrlUtils.MY_APPLY_LIST;

/**
 * @author Lenovo
 */
public class WebViewActivity extends BaseActivity {
    private WebView mWebView;
    private SpinKitView spinKitView;
    private List<String> stringList = new ArrayList<>();

    private ApplyRecordBean applyRecordBean;
    private List<ApplyRecordBean.DataBean> dataBeans = new ArrayList<>();

    private boolean isShowFloat = true;  // 是否显示浮层

    private String linkAppid;
    private String title;

    private boolean isBindService;
    private Dialog loadingDialog;
    private ProgressBar progressBar;
    private TextView tv_desc;
    private TextView tv_countdown;

    private CountDownTimer timer;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        title = getIntent().getStringExtra("title");
        if (isFinish()) {
            myApplyDk();
            setContent();
        }
        initWeb();
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
            DownloadService downloadService = binder.getService();
            downloadService.setTargetActivity(WebViewActivity.this);
            //接口回调，下载进度
            downloadService.setOnProgressListener(new DownloadService.OnProgressListener() {
                @Override
                public void onProgress(float fraction) {
                    progressBar.setProgress((int) (fraction * 100));
                    tv_desc.setText(String.format(Locale.getDefault(), "%d%%", (int) (fraction * 100)));
                    if (fraction == 1 && isBindService) {
                        unbindService(conn);
                        isBindService = false;
                        if (loadingDialog != null) {
                            loadingDialog.dismiss();
                        }
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @SuppressLint("SetJavaScriptEnabled")
    private void initWeb() {
        initToolbar(title);
        spinKitView = (SpinKitView) findViewById(R.id.spin_kit);
        mWebView = (WebView) findViewById(R.id.wv_view);
        ibNews.setVisibility(View.VISIBLE);
        ibNews.setImageDrawable(getResources().getDrawable(R.mipmap.icon_close));
        ibNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowFloat();
            }
        });
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                spinKitView.setVisibility(View.VISIBLE);
                stringList.add(view.getUrl());
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                spinKitView.setVisibility(View.GONE);
                if (stringList.size() > 2) {
                    removeDuplicate(stringList);
                }
            }


        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                downloadByBrowser(url);
            }
        });
        LogUtil.i(getIntent().getStringExtra("url")+" ******  ");
        mWebView.loadUrl(getIntent().getStringExtra("url"));
        //mWebView.loadUrl("https://mp.weixin.qq.com/s/jaY_UTBE6DRrWYV9dLM7XQ");
        mIbReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFinish()) {
                    if (Objects.requireNonNull(SPUtil.getInfoBean()).getPage() > 0 && isShowFloat) {
                        startActivity();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
            }
        });
    }

    private void downloadByBrowser(String url) {
        downloadDialog();
        isBindService = true;
        Map<String, String> params = new HashMap<>();
        params.put("name", title);
        params.put("openid", SPUtil.getUserInfo().getOpenid());
        MobclickAgent.onEvent(SqjAppliaction.getContext(), "downloadApp", params);
        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra("url", url);
        intent.putExtra("name", title);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
//        UpdateFragment.showFragment(this,
//                false, url, title, "下载中，预计9秒，请勿离开……", BuildConfig.APPLICATION_ID);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isFinish()) {
            if (Objects.requireNonNull(SPUtil.getInfoBean()).getPage() > 0 && isShowFloat) {
                startActivity();
                return true;
            } else {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (stringList.size() > 1) {
                        mWebView.loadUrl(stringList.get(stringList.size() - 1));
                        if (stringList.size() > 2) {
                            stringList.clear();
                        }
                    } else {
                        finish();
                        return true;
                    }
                    return true;
                }
            }
        } else {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public static void removeDuplicate(List<String> list) {
        HashSet<String> h = new HashSet<String>(list);
        list.clear();
        list.addAll(h);
        list.remove(list.size() - 1);
    }

    /**
     * 申请列表
     */
    private void myApplyDk() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(MY_APPLY_LIST, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                applyRecordBean = JSON.parseObject(jsonString, ApplyRecordBean.class);
                for (ApplyRecordBean.DataBean dataBean : applyRecordBean.getData()) {
                    if (TimeUtils.longToString(dataBean.getSq().getTime()).equals(TimeUtils.nowTime())) {
                        dataBeans.add(dataBean);
                    }
                    if (title.equals(dataBean.getChanpin().getName())) {
                        linkAppid = dataBean.getSq().getLinkappid();
                        if (dataBean.getSq().getXiazai().equals("已下载")) {
                            isShowFloat = false;
                        } else {
                            isShowFloat = true;
                        }
                    }
                }

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void isShowFloat() {
        if (isFinish()) {
            if (Objects.requireNonNull(SPUtil.getInfoBean()).getPage() > 0 && isShowFloat) {
                startActivity();
            } else {
                if (stringList.size() > 1) {
                    mWebView.loadUrl(stringList.get(stringList.size() - 1));
                    if (stringList.size() > 2) {
                        stringList.clear();
                    }
                } else {
                    finish();
                }
            }
        } else {
            finish();
        }
    }

    public void startActivity() {
        Intent intent = new Intent(this, FloatingLayerActivity1.class);
        intent.putExtra("applyNum", dataBeans.size());
        intent.putExtra("linkAppId", linkAppid);
        intent.putExtra("title", getIntent().getStringExtra("title"));
        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        initWeb();
    }

    public void setContent() {
        ClipboardManager clipboard =
                (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("Label", Objects.requireNonNull(SPUtil.getUserInfo()).getOpenid()));
        ToastUtils.show("手机号已复制，可直接粘贴");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBindService) {
            unbindService(conn);
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (timer != null) {
            timer.cancel();
        }
    }


    public void downloadDialog() {
        loadingDialog = new Dialog(this, R.style.CustomProgressDialog);// 创建自定义样式dialog
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setCancelable(true);// 可以用“返回键”取消
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_update_app, null);
        loadingDialog.setContentView(view);// 设置布局
        if (AppUtils.getAppMetaData(this, "UMENG_CHANNEL").equals("huawei")) {
            view.findViewById(R.id.ll_install_tip).setVisibility(View.VISIBLE);
        } else {
            view.findViewById(R.id.ll_install_tip).setVisibility(View.GONE);
        }
        loadingDialog.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        progressBar = view.findViewById(R.id.progress);
        tv_countdown = view.findViewById(R.id.tv_countdown);
        tv_desc = view.findViewById(R.id.tv_desc);
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingDialog.dismiss();
            }
        });
        loadingDialog.show();
        countDownTime(15);
    }

    private boolean isFinish() {
        return !title.equals(getResources().getString(R.string.user_xy))
                && !title.equals(getResources().getString(R.string.black))
                && !title.equals(getResources().getString(R.string.cns))
                && !title.equals(getResources().getString(R.string.yss))
                && !title.equals(getResources().getString(R.string.xys))
                && !title.equals(getResources().getString(R.string.vip_xy));
    }


    public void countDownTime(int time) {
        /** 倒计时60秒，一次1秒 */
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                tv_countdown.setText(String.format(Locale.getDefault(), "下载中，预计%d秒，请勿离开……", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                tv_countdown.setText(String.format(Locale.getDefault(), "下载中，预计%d秒，请勿离开……", 0));
            }
        }.start();
    }

}
